package com.dlwx.parttimetalent.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.ImageView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.baidu.LocationService;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.base.MyApplication;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapActivity extends BaseActivity {

    @BindView(R.id.bmapView)
    MapView mMapView;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    private static BaiduMap mBaiduMap;
    private static  boolean isFirst=true;
    public String lat, longi;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadingDialog.dismiss();
//            firstLocation();
            addPoint();
        }
    };
    private mBroadcastReceiver receiver;
    private LocationService locationService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_by);
        ButterKnife.bind(this);
        loadingDialog.show();
         locationService = ((MyApplication) getApplication()).locationService;
        locationService.stop();
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                mHandler.sendEmptyMessageDelayed(0,1000);
                locationService.start();
            }
        });
        isFirst=true;
        receiver=new mBroadcastReceiver();
        registerReceiver(receiver,new IntentFilter("com.dlwx.location"));
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    /**
     * 第一次进入地图快速定位
     */
//    private void firstLocation(){
//        longi = (String) SPUtils.get(this, Constant.LOCATION_LON, "116.395645");
//        lat = (String) SPUtils.get(this, Constant.LOCATION_LAT, "39.929985");
//        try {
//            double longDou=Double.parseDouble(longi);
//            double latDou=Double.parseDouble(lat);
//            LatLng latLng = new LatLng(latDou, longDou);
//            moveToPoint(latLng,true);
//        }catch (Exception e){
//            LogUtils.i(e.toString());
//        }
//    }

    /***
     * 添加订单marker
     */
    private static LatLng markLatlng=null;
    private void addPoint() {
        String headurl = getIntent().getStringExtra("headurl");
//        Glide.with(this).load(headurl)
        Double lon = getIntent().getDoubleExtra("lon", 0);
        Double lat = getIntent().getDoubleExtra("lat", 0);
        Double latDouble = null, lonDouble = null;

        //定义Maker坐标点
        markLatlng = new LatLng(lat, lon);
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.yong);
//构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(markLatlng)
                .icon(bitmap);
//在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(markLatlng)
                .zoom(16)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);

    }

    private static void initLocation(BDLocation location) {
        // 开启定位图层
        if(mBaiduMap==null){
            return;
        }
        mBaiduMap.setMyLocationEnabled(true);

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        if(isFirst){
// 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
// 设置定位数据
            mBaiduMap.setMyLocationData(locData);

// 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                    .fromResource(R.mipmap.wo);
            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, false, mCurrentMarker);

            List<LatLng> points = new ArrayList<LatLng>();
            points.add(markLatlng);
            points.add(latLng);
            if(points!=null&&!points.contains((LatLng)null)){
                //绘制折线
                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                        .color(Integer.valueOf(Color.BLUE)).points(points);
                Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
                isFirst=false;
                mBaiduMap.setMyLocationConfigeration(config);
            }
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(latLng)
                    .zoom(16)
                    .build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mBaiduMap.animateMapStatus(mMapStatusUpdate);
        }

    }

    private static void moveToPoint(LatLng latLng) {
        if(isFirst){
            List<LatLng> points = new ArrayList<LatLng>();
            points.add(markLatlng);
            points.add(latLng);
            if(points!=null&&!points.contains((LatLng)null)){
                //绘制折线
                OverlayOptions ooPolyline = new PolylineOptions().width(10)
                        .color(Integer.valueOf(Color.BLUE)).points(points);
                Polyline mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
                isFirst=false;
            }
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(latLng)
                    .zoom(16)
                    .build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mBaiduMap.animateMapStatus(mMapStatusUpdate);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationService.stop();
        // 当不需要定位图层时关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }



    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
           try {
               unregisterReceiver(receiver);
           }catch (Exception e){
           }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
    }
    @OnClick(R.id.title_left_one_btn)
    public void onViewClicked() {
        this.finish();
    }

    public static class mBroadcastReceiver extends BroadcastReceiver {
        public mBroadcastReceiver() {
        }
        //接收到广播后自动调用该方法
        @Override
        public void onReceive(Context context, Intent intent) {
            //写入接收广播后的操作
            if(TextUtils.equals(intent.getAction(),"com.dlwx.location")){
                BDLocation location= intent.getParcelableExtra("location");
                    initLocation(location);
            }
        }
    }
}
